package com.springboot.cloud.common.core.jiguang;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jmessage.api.JMessageClient;
import cn.jmessage.api.common.model.RegisterInfo;
import cn.jmessage.api.common.model.UserPayload;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSONObject;
import com.springboot.cloud.common.core.entity.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static cn.jpush.api.push.model.notification.PlatformNotification.ALERT;

@Configuration
@Component
@Slf4j
public class JpushUtil {

    @Value("${jiguang.appkey}")
    private String appkey;

    @Value("${jiguang.masterSecret}")
    private String masterSecret;
    JPushClient jpushClient;

    public PushPayload buildPushObject_all_all_alert() {
        return PushPayload.alertAll(ALERT);
    }

    /**
     * 构建视频通话请求推送
     */
    public PushPayload buildVideoPayLoad(String nickname, String registrationId, String type, String status, String channelName, String userId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", type);
        jsonObject.put("status", status);
        jsonObject.put("channelName", channelName);
        jsonObject.put("userId", userId);
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.registrationId(registrationId))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(nickname + (status.equals("start") ? "向你发起了通话请求" : "挂断了通话请求"))
                                .setBadge(5)
                                .setSound("happy")
                                .addExtra("type", type)
                                .addExtra("status", status)
                                .addExtra("channelName", channelName)
                                .addExtra("userId", userId)
                                .build())
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(nickname + (status.equals("start") ? "向你发起了通话请求" : "挂断了通话请求"))
                                .addExtra("type", type)
                                .addExtra("status", status)
                                .addExtra("channelName", channelName)
                                .addExtra("userId", userId)
                                .build())
                        .build())
                .setMessage(Message.content(jsonObject.toJSONString()))
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .build())
                .build();

    }

    /**
     * 构建message推送
     *
     * @param registrationId 接收者注册ID
     * @param messageId      消息ID
     * @param title          标题
     */
    public PushPayload buildMessagePayLoad(String registrationId, String messageId, String title) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.registrationId(registrationId))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(title)
                                .setBadge(5)
                                .setSound("happy")
                                .addExtra("messageId", messageId)
                                .build())
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(title)
                                .addExtra("messageId", messageId)
                                .build())
                        .build())
                .setMessage(Message.content(title))
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .build())
                .build();
    }

    public JPushClient getJpushClient() {
        if (jpushClient == null) {
            jpushClient = new JPushClient(masterSecret, appkey, null, ClientConfig.getInstance());
        }
        return jpushClient;
    }

    public Result send(PushPayload payload) {

        jpushClient = getJpushClient();
        try {
            PushResult result = jpushClient.sendPush(payload);
            if (result.statusCode == 200) {
                return Result.success();
            }
            log.info("Got result - " + result);

        } catch (APIConnectionException e) {
            // Connection error, should retry later
            log.error("Connection error, should retry later", e);

        } catch (APIRequestException e) {
            // Should review the error, and fix the request
            log.error("Should review the error, and fix the request", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
        }
        return Result.fail();
    }
}
